const path = require('path');
const { request, uploadFiles } = require('@seeyon/node-tools');
const { name, buildVersion, clientParams } = require('./utils');
const { resolveApp } = require('./resolve');
const rimraf = require('rimraf');
const { execSync } = require('child_process');

const params = {
  uploadTargetType: 'ali',
  clientParams: { ...clientParams, ...{ bucket: 'seeyon-frontend' } },
  bucketName: '',
  sourceFloder: process.env.VENDOR ? path.resolve(__dirname, '../vendors') : resolveApp('dist'),
  targetFloder: process.env.VENDOR ? '/dev/static' : `/${name}/${buildVersion}`,
  // : `/dev/${name}/${moment().format('1.0.0')}`,
};
(() => {
  const branch = execSync('git rev-parse --abbrev-ref HEAD').toString();
  if (!branch.startsWith('dev')) {
    // 检测部署的分支是否为dev
    console.log('\x1b[31m❌请将代码合并到dev分支，当前分支：%s\x1b[0m', branch);
    process.exit(1);
  }
  console.log('\x1b[34m分支检测 ok\x1b[0m');
  const hasChangeFile = execSync('git status').toString();
  if (hasChangeFile.indexOf('git add') > 0) {
    // 检测是否有未提交的代码
    console.log('\x1b[31m❌本地有未提交的代码，请先与远程分支进行同步\x1b[0m');
    process.exit(1);
  }
  console.log('\x1b[34m暂存区检测 ok\x1b[0m');
  const devHash = execSync('git fetch origin && git rev-parse --short origin/dev').toString();
  const localHash = execSync('git fetch origin && git rev-parse --short HEAD').toString();
  if (devHash !== localHash) {
    // 检测本地commit与远程是否一致
    console.log('\x1b[31m❌本地分支不是最新代码，请先与远程分支进行同步\x1b[0m');
    process.exit(1);
  }
  console.log('\x1b[34m工作区检测 ok\x1b[0m');
  rimraf.sync('yarn.lock'); // 删除yarnlock
  execSync('yarn', { stdio: 'inherit' });
  console.log('\x1b[34m依赖安装 ok\x1b[0m');
  execSync('yarn build', { stdio: 'inherit' });
  console.log('\x1b[34m本地构建 ok\x1b[0m');
  uploadFiles(params)
    .then(
      function () {
        console.log('\x1b[34m上传远端云存储 ok\x1b[0m');
        request({
          url: 'http://sy-dev.seeyonv8.com/service/ctp-manager/ctp-manager-app/create',
          data: { appName: name, appVersion: buildVersion, env: 'dev' },
        }).then(() => {
          console.log('\x1b[34m版本号更新成功 %s\x1b[0m', buildVersion);
        }),
          (rej) => {
            console.log('\x1b[31m❌版本号更新失败 %s\x1b[0m', rej);
            process.exit(1);
          };
      },
      function (rej) {
        const newError = rej instanceof Error ? String(rej) : JSON.stringify(rej);
        console.log('\x1b[31m❌REJECT %s\x1b[0m', newError);
        process.exit(1);
      },
    )
    .catch(function (error) {
      const newError = error instanceof Error ? String(error) : JSON.stringify(error);
      console.log('\x1b[31m❌ERROR %s\x1b[0m', newError);
      process.exit(1);
    });
})();
